Page({
  data: {
    // 完整的分类和型号数据
    categories: [
      {
        id: 'tdc',
        name: 'TDC系列',
        models: [
          { id: 'tdc2', name: 'TDC 2', nanoloy: 'NDC20N-02M' },
          { id: 'tdc3', name: 'TDC 3', nanoloy: 'NDC30N-02M' },
          { id: 'tdc4', name: 'TDC 4', nanoloy: 'NDC40N-03M' },
          { id: 'tdc5', name: 'TDC 5', nanoloy: 'NDC50N-03M' },
          { id: 'tdc6', name: 'TDC 6', nanoloy: 'NDC60N-03M' },
          { id: 'tdc8', name: 'TDC 8', nanoloy: '-' }
        ]
      },
      {
        id: 'tdt-ru',
        name: 'TDT-RU系列',
        models: [
          { id: 'tdt2e10', name: 'TDT 2E-1.0', nanoloy: 'NDT20R-10M' },
          { id: 'tdt3e15', name: 'TDT 3E-1.5', nanoloy: 'NDT30R-15M' },
          { id: 'tdt4e20', name: 'TDT 4E-2.0', nanoloy: 'NDT40R-20M' },
          { id: 'tdt5e25', name: 'TDT 5E-2.5', nanoloy: 'NDT50R-25M' }
        ]
      },
      {
        id: 'tdt',
        name: 'TDT系列',
        models: [
          { id: 'tdt3', name: 'TDT 3', nanoloy: 'NDT30N-04M' },
          { id: 'tdt4', name: 'TDT 4', nanoloy: 'NDT40N-04M' },
          { id: 'tdt5e04', name: 'TDT 5E-0.4', nanoloy: 'NDT50N-04M' },
          { id: 'tdt6e08', name: 'TDT 6E-0.8', nanoloy: 'NDT60N-08M' }
        ]
      },
      {
        id: 'tdxu',
        name: 'TDXU系列',
        models: [
          { id: 'tdxu2e03', name: 'TDXU 2E-0.3', nanoloy: '-' },
          { id: 'tdxu3e03', name: 'TDXU 3E-0.3', nanoloy: 'NDXU3E-0.3' },
          { id: 'tdxu4e04', name: 'TDXU 4E-0.4', nanoloy: 'NDXU4E-0.4' },
          { id: 'tdxu4e08', name: 'TDXU 4E-0.8', nanoloy: '-' },
          { id: 'tdxu5e04', name: 'TDXU 5E-0.4', nanoloy: '-' },
          { id: 'tdxu5e08', name: 'TDXU 5E-0.8', nanoloy: '-' },
          { id: 'tdxu6e04', name: 'TDXU 6E-0.4', nanoloy: '-' },
          { id: 'tdxu6e08', name: 'TDXU 6E-0.8', nanoloy: '-' },
          { id: 'tdxu8e08', name: 'TDXU 8E-0.8', nanoloy: '-' }
        ]
      },
      {
        id: 'tdj',
        name: 'TDJ系列',
        models: [
          { id: 'tdj2', name: 'TDJ 2', nanoloy: 'NDJ20N-02M' },
          { id: 'tdj3', name: 'TDJ 3', nanoloy: 'NDJ30N-02M' },
          { id: 'tdj4', name: 'TDJ 4', nanoloy: 'NDJ40N-03M' },
          { id: 'tdj5', name: 'TDJ 5', nanoloy: '-' },
          { id: 'tdj6', name: 'TDJ 6', nanoloy: '-' },
          { id: 'tdj215l', name: 'TDJ2-15L', nanoloy: 'NDJ20L-02G-15' }
        ]
      }
    ],
    currentCategory: null,
    filteredModels: [],
    cart: [],
    materialNL6025: false,
    materialNL6045: false,
    activeIndex: -1,
    quantity: 200,
    cartTotal: 0,
    cartQuantity: 0
  },

  onLoad: function() {
    // 数据加载验证
    if (!this.data.categories || this.data.categories.length === 0) {
      console.error('分类数据加载失败！');
      wx.showToast({
        title: '数据加载失败',
        icon: 'error'
      });
      return;
    }

    // 初始化显示所有型号，不进行过滤
    this.setData({
      currentCategory: this.data.categories[0],
      filteredModels: this.data.categories[0].models
    });
  },

  switchCategory: function(e) {
    const categoryId = e.currentTarget.dataset.id;
    const category = this.data.categories.find(c => c.id === categoryId);
    if (category) {
      this.setData({
        currentCategory: category,
        filteredModels: category.models // 显示所有型号不过滤
      });
    }
  },

  onQuantityChange: function(e) {
    const value = parseInt(e.detail.value) || 0;
    this.setData({
      quantity: value
    });
  },

  onQuantityTap: function(e) {
    // 获取输入框元素
    const query = wx.createSelectorQuery();
    query.select('.quantity-field').fields({
      properties: ['value']
    }, function(res) {
      // 如果当前有值，则清空；如果为空，则设置为默认值200
      const newValue = res.value ? '' : '200';
      this.setData({
        quantity: newValue
      });
    }.bind(this)).exec();
  },

  // 获取型号对应的价格
  getModelPrice: function(modelName) {
    // 提取型号中的数字
    const match = modelName.match(/\d+/);
    if (!match) return 0;
    
    const size = parseInt(match[0]);
    switch(size) {
      case 2: return 20;
      case 3: return 21;
      case 4: return 22;
      default: return 0;
    }
  },

  // 更新购物车总计
  updateCartTotal: function() {
    const total = this.data.cart.reduce((sum, item) => sum + item.total, 0);
    const quantity = this.data.cart.reduce((sum, item) => sum + item.quantity, 0);
    this.setData({
      cartTotal: total,
      cartQuantity: quantity
    });
  },

  // 型号点击处理
  handleModelClick: function(e) {
    const index = e.currentTarget.dataset.index;
    const modelId = e.currentTarget.dataset.id;
    
    // 设置点击效果
    this.setData({ activeIndex: index });
    
    // 添加到购物车
    const model = this.data.filteredModels[index];
    if (!model || model.nanoloy === '-') return; // 不添加无效型号

    const newItems = [];
    const { materialNL6025, materialNL6045, quantity } = this.data;
    const price = this.getModelPrice(model.name);
    const total = price * quantity;

    if (materialNL6025) {
      newItems.push({
        id: model.id + '_6025',
        name: model.name,
        nanoloy: model.nanoloy,
        price: price,
        quantity: quantity,
        total: total,
        displayText: `${model.nanoloy} NL6025未税${price}*${quantity}=${total}`
      });
    }
    if (materialNL6045) {
      newItems.push({
        id: model.id + '_6045',
        name: model.name,
        nanoloy: model.nanoloy,
        price: price,
        quantity: quantity,
        total: total,
        displayText: `${model.nanoloy} NL6045未税${price}*${quantity}=${total}`
      });
    }

    if (newItems.length === 0) {
      newItems.push({
        id: model.id,
        name: model.name,
        nanoloy: model.nanoloy,
        price: price,
        quantity: quantity,
        total: total,
        displayText: `${model.nanoloy}未税${price}*${quantity}=${total}`
      });
    }

    this.setData({
      cart: [...this.data.cart, ...newItems],
      activeIndex: -1 // 立即重置点击状态
    });
    
    this.updateCartTotal(); // 更新总计
    
    wx.showToast({
      title: '已添加',
      icon: 'success',
      duration: 500
    });
  },

  removeFromCart: function(e) {
    const index = e.currentTarget.dataset.index;
    const newCart = [...this.data.cart];
    newCart.splice(index, 1);
    this.setData({ cart: newCart });
    this.updateCartTotal(); // 更新总计
  },

  onMaterialChange: function(e) {
    const values = e.detail.value;
    this.setData({
      materialNL6025: values.includes('NL6025'),
      materialNL6045: values.includes('NL6045')
    });
  },

  copyCartItems: function() {
    if (this.data.cart.length === 0) {
      wx.showToast({ title: '购物车为空', icon: 'none' });
      return;
    }
    
    // 计算总计
    const total = this.data.cart.reduce((sum, item) => sum + item.total, 0);
    const quantity = this.data.cart.reduce((sum, item) => sum + item.quantity, 0);
    
    // 构建复制内容
    const contentToCopy = this.data.cart.map(item => item.displayText).join('\n') + 
                         '\n总计：' + quantity + '片 ' + total + '元';
    
    wx.setClipboardData({
      data: contentToCopy,
      success: () => {
        wx.showToast({ title: '复制成功' });
      }
    });
  },

  clearCart: function() {
    wx.showModal({
      title: '确认清空',
      content: '是否清空所有已选型号？',
      success: (res) => {
        if (res.confirm) {
          this.setData({ 
            cart: [],
            cartTotal: 0
          });
          wx.showToast({
            title: '已清空',
            icon: 'success',
            duration: 500
          });
        }
      }
    });
  }
});